package com.xiaodou.mjf.web.console.basic.interceptor;


import com.xiaodou.mjf.application.basic.service.MenuService;
import com.xiaodou.mjf.application.basic.utils.OperatorUtils;
import com.xiaodou.mjf.entity.basic.Menu;
import com.xiaodou.mjf.infrastructure.common.context.SpringContextHolder;
import com.xiaodou.mjf.infrastructure.common.utils.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Rocky on 14/12/20.
 */
public class MenuHandlerInterceptor implements HandlerInterceptor {

    MenuService menuService = SpringContextHolder.getBean(MenuService.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

        String context = request.getContextPath();
        String uri = request.getRequestURI();

        if (uri.indexOf("login") != -1 || uri.indexOf("resources") != -1) {
        } else {
            if (StringUtils.isNotBlank(context)) {
                uri = uri.replace(context, StringUtils.EMPTY);
            }
            Menu menu = null;

            if (uri.equals("/")) {
                menu = menuService.getMenuByUrl(uri);
                
            } else {

                for (Menu e : OperatorUtils.getMenuList()) {
                	//System.out.println(e.getName());
                    if (StringUtils.isNotBlank(e.getUrl()) && !e.getUrl().equals("/") && (uri.equals(e.getUrl()) || uri.startsWith(e.getUrl()))) {
                        menu = e;
                        //break;
                    }
                }
            }
            if (menu != null) {
                if (uri.equals("/")) {
                    request.setAttribute("menuId", menu.getId());
                } else {
                    request.setAttribute("menuId", menu.getParent().getId());
                    request.setAttribute("subMenuId", menu.getId());
                }
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
